package pers.kw.config.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import pers.kw.config.properties.OAuthConfigProperties;
import pers.kw.config.security.MyUserDetailsService;

import java.util.Arrays;

/**
 * OAuth配置
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final MyUserDetailsService myUserDetailsService;
    private final OAuthConfigProperties authConfigProperties;
    private final MyClientDetailService myClientDetailService;
    private final TestMyClientDetailService testMyClientDetailService;

    private final MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    private final CustomBasicAuthenticationFilter customBasicAuthenticationFilter;

    @Autowired
    public AuthorizationServerConfig(
            MyAuthenticationEntryPoint myAuthenticationEntryPoint,
            CustomBasicAuthenticationFilter customBasicAuthenticationFilter,
            MyClientDetailService myClientDetailService,
            OAuthConfigProperties authConfigProperties,
            AuthenticationManager authenticationManager,
            MyUserDetailsService myUserDetailsService,
            TestMyClientDetailService testMyClientDetailService) {
        this.myAuthenticationEntryPoint = myAuthenticationEntryPoint;
        this.customBasicAuthenticationFilter = customBasicAuthenticationFilter;
        this.authenticationManager = authenticationManager;
        this.myUserDetailsService = myUserDetailsService;
        this.authConfigProperties = authConfigProperties;
        this.myClientDetailService = myClientDetailService;
        this.testMyClientDetailService = testMyClientDetailService;
    }

    /**
     * 授权服务安全认证配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //允许表单认证客户端信息
        //在自定义客户端异常处理过滤器时，不能开启这个，否则会导致过滤器失效，仍使用原来的
        //security.allowFormAuthenticationForClients();

        //自定义客户端异常处理过滤器（表单传参才有效）
        //basic auth或 http://hbr:hbr@localhost:8080 这两种传参方式无效
        MyClientCredentialsTokenEndpointFilter myClientCredentialsTokenEndpointFilter =
                new MyClientCredentialsTokenEndpointFilter(security);
        myClientCredentialsTokenEndpointFilter.afterPropertiesSet();
        myClientCredentialsTokenEndpointFilter.setAuthenticationEntryPoint(myAuthenticationEntryPoint);
        //security.addTokenEndpointAuthenticationFilter(myClientCredentialsTokenEndpointFilter);

        //basic方式认证才有效
        security.addTokenEndpointAuthenticationFilter(customBasicAuthenticationFilter);
    }

    /**
     * 客户端信息配置
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(myClientDetailService);
        //clients.withClientDetails(testMyClientDetailService);
    }

    /**
     * 授权服务端点配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.userDetailsService(myUserDetailsService);
        //认证管理器
        endpoints.authenticationManager(authenticationManager);

        //自定义异常信息返回值（授权码模式、密码模式）
        endpoints.exceptionTranslator(new MyWebResponseExceptionTranslator());

        //设置token请求方式
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST);

        //token信息配置
        endpoints.tokenServices(tokenServices());
    }


    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setTokenEnhancer(tokenEnhancerChain());

        OAuthConfigProperties.OAuthToken oauthToken = authConfigProperties.getOauthToken();
        //统一在客户端配置
        tokenServices.setAccessTokenValiditySeconds(oauthToken.getAccessTokenValiditySeconds());
        tokenServices.setRefreshTokenValiditySeconds(oauthToken.getRefreshTokenValiditySeconds());
        tokenServices.setSupportRefreshToken(true);

        //客户端信息配置，开启配置取
        tokenServices.setClientDetailsService(myClientDetailService);
        return tokenServices;
    }

    @Bean
    public TokenEnhancerChain tokenEnhancerChain() {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        return tokenEnhancerChain;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //使用非对称加密算法
        OAuthConfigProperties.OAuthToken oauthToken = authConfigProperties.getOauthToken();
        jwtAccessTokenConverter.setSigningKey(oauthToken.getSigningKey());
        jwtAccessTokenConverter.setVerifierKey(oauthToken.getVerifierKey());
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new JwtTokenEnhancer();
    }
}
